﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RungSoft.RungEBookMaker.Providers.DocFormater.Exceptions;

namespace RungSoft.RungEBookMaker.Providers.DocFormater
{
    [Serializable]
    internal abstract class BookBase
    {
        protected Encoding mEncoding = Encoding.Unicode;
        protected DateTime mDate = DateTime.Now;
        protected ProjectBM mProjectBM;

        /// <summary>
        /// 书名
        /// </summary>
        internal string Title
        {
            get;
            set;
        }

        /// <summary>
        /// 书籍保存的目录
        /// </summary>
        internal string FilePath
        {
            get;
            set;
        }

        internal Encoding Encoding
        {
            get
            {
                return this.mEncoding;
            }
        }

        /// <summary>
        /// 作者
        /// </summary>
        internal string Author
        {
            get;
            set;
        }

        /// <summary>
        /// 发行日期
        /// </summary>
        internal DateTime Date
        {
            get { return this.mDate; }
        }

        /// <summary>
        /// 生成项目
        /// </summary>
        internal ProjectBM ToProject()
        {
            return new ProjectBM
            {
                Book = this,
                BookClass = this.GetType().ToString(),
                BuildTime = DateTime.Now
            };
        }

        /// <summary>
        /// 保存项目
        /// </summary>
        internal void SaveAsProject(string filePath)
        {
            if (string.IsNullOrEmpty(this.Title)) throw (new MetaInfoNullException("标题不能为空。"));

            filePath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase, filePath, this.Title + ".ebp");
            this.ToProject().Save(filePath);
        }

        internal virtual void LoadByProject(string filePath)
        {
            filePath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase, filePath, this.Title + ".ebp");
            if (System.IO.File.Exists(filePath) == false) throw (new ProjectFileNotFunndException("项目文件不存在。"));

            this.mProjectBM = ProjectBM.Load(filePath);
            if (this.mProjectBM == null) throw (new ProjectFormateException("项目文件格式错误（1）。"));

            this.mDate = this.mProjectBM.Book.Date;
            this.mEncoding = this.mProjectBM.Book.Encoding;
        }
    }
}
